﻿using System;
using System.Collections.Generic;
using System.Linq;
using Lucene.Linq.Mapping;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Lucene.Linq.Search;

namespace Lucene.Linq.VSTests
{
    [TestClass]
    public class TestSearchingForHits
    {
        [TestMethod]
        public void Searching_for_hits_returns_document_id_and_score()
        {
            using (var i = new Index<Thing>())
            {
                i.Add(Thing.GetRandom(40));


                IQueryable<Thing> results = from item in i
                                            where item.Name == "thing"
                                            select item;

                Console.Write("Result count {0}", results.Count());
                Assert.IsTrue(results.Count() != 0);

                foreach (Thing result in results)
                {
                    Assert.IsTrue(result.DocumentId >= 0);
                    Assert.IsTrue(result.Relevance > 0);
                }
            }
        }

        #region Nested type: Thing

        [Document]
        public class Thing : IHit
        {
            private static readonly Random random = new Random();

            [Field(FieldIndex.Tokenized, FieldStore.Yes, IsKey = true, IsDefault = true)]
            public string Name { get; set; }

            #region IHit Members

            public int DocumentId { get; set; }
            public float Relevance { get; set; }

            #endregion

            private static string RepeatWord(string word, int num)
            {
                var words = new string[num];

                for (int i = 0; i < words.Length; i++)
                    words[i] = word;

                return String.Join(" ", words);
            }

            public static IEnumerable<Thing> GetRandom(int num)
            {
                int i = 0;

                while (num > i)
                {
                    yield return new Thing
                                     {
                                         Name = RepeatWord("thing", random.Next(10))
                                     };

                    i++;
                }
            }
        }

        #endregion
    }
}